//
//  NSString+Utils.m
//  LPA_C2C
//
//  Created by HuangYingjie on 15/11/2.
//  Copyright © 2015年 yixin. All rights reserved.
//

#import "NSString+Utils.h"
#import <CommonCrypto/CommonDigest.h>
#include <netdb.h>
#include <arpa/inet.h>

@implementation NSString (Utils)

- (NSString *)trimedString
{
    if (self)
    {
        NSString *trimedStr = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        return trimedStr;
    }
    
    return self;
}

- (CGSize)boundingRectWithSize:(CGSize)size font:(UIFont *)font
{
    NSDictionary *attributes = @{NSFontAttributeName:font};
    CGSize tsize = [self boundingRectWithSize:size options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    
    return tsize;
}

//获取拼音首字母(传入汉字字符串, 返回大写拼音首字母)
- (NSString *)firstCharactor
{
    // 转成可变字符串
    NSMutableString *str = [[NSMutableString alloc] initWithString:self];
    // 先转换为带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    // 再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    // 转化为大写拼音
    NSString *pinYin = [str capitalizedString];
    //获取并返回首字母
    return [pinYin substringToIndex:1];
}

//获取拼音首字母(传入汉字字符串, 返回汉字拼音
- (NSString *)pinYinCharactor
{
    // 转成可变字符串
    NSMutableString *str = [[NSMutableString alloc] initWithString:self];
    // 先转换为带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    // 再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    // 转化为大写拼音
    NSString *pinYin = [[str trimedString] stringByReplacingOccurrencesOfString:@" " withString:@""];
    return [pinYin length] > 0 ? [pinYin lowercaseString] : nil;
}

#pragma mark-- 替换字符串
- (NSString *)replaceWithstr:(NSString *)str
{
    NSMutableString *responseString = [NSMutableString stringWithString:str];
    NSString *character = nil;
    for (int i = 0; i < responseString.length; i++) {
        character = [responseString substringWithRange:NSMakeRange(i, 1)];
        if ([character isEqualToString:@"\n"])
            [responseString deleteCharactersInRange:NSMakeRange(i, 1)];
    }
    
    return responseString;
}

- (CGSize)sizeWithBoundingRectSize:(CGSize)rectSize attributeFont:(UIFont *)attributeFont {
    
    if ([self isKindOfClass:[NSNull class]] || self.length == 0) {
        return CGSizeZero;
    }
    
    NSDictionary *attributes = @{NSFontAttributeName: attributeFont};
    
    CGSize stringSize = [self boundingRectWithSize:rectSize
                                           options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                        attributes:attributes
                                           context:nil].size;
    
    return CGSizeMake(ceilf(stringSize.width), ceilf(stringSize.height));
}

////////////////////////////////////////////////////////////////////////////////////////////

- (NSAttributedString *)strikethrough
{
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    [attrs setValue:@(NSUnderlineStyleSingle|NSUnderlinePatternSolid) forKey:NSStrikethroughStyleAttributeName];
    [attrs setValue:@(0) forKey:NSBaselineOffsetAttributeName];
    return [[NSAttributedString alloc] initWithString:self attributes:attrs];
}

+ (NSMutableAttributedString *)separatePhone:(NSString *)phone
{
    if (!phone) {
        return nil;
    }
    CGFloat spacing = 5.0;
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:phone];
    if (phone.length > 3) {
        [attr addAttribute:NSKernAttributeName value:@(spacing) range:NSMakeRange(2, 1)];
    }
    if (phone.length > 7) {
        [attr addAttribute:NSKernAttributeName value:@(spacing) range:NSMakeRange(6, 1)];
    }
    
    return attr;
}

+ (NSMutableAttributedString *)hyphenWithName:(NSString *)name mode:(NSString *)mode color:(UIColor *)color
{
    NSMutableAttributedString *attr;
    if (mode.length > 0) {
        NSString *newStr = [NSString stringWithFormat:@"%@-%@",mode,name];
        attr = [[NSMutableAttributedString alloc] initWithString:newStr];
        [attr addAttribute:NSForegroundColorAttributeName
                     value:color
                     range:NSMakeRange(0, mode.length + 1)];

    } else {
        attr = [[NSMutableAttributedString alloc] initWithString:name];
    }

    return attr;
}

- (NSString *)tenThousandStyle
{
    NSString *result = nil;
    CGFloat num = [self floatValue];
    if (num > 10000) {
        num /= 10000;
        result = [NSString stringWithFormat:@"%.2f万",num];
    } else {
        result = [NSString stringWithFormat:@"%.0f",num];
    }
    return result;
}

/**
 返回ip地址 self为domain
 
 @return
 */
- (NSString *)getIpAddress
{
    struct hostent *hs;
    struct sockaddr_in server;
    if ((hs = gethostbyname([self UTF8String])) != NULL)
    {
        server.sin_addr = *((struct in_addr*)hs->h_addr_list[0]);
        return [NSString stringWithUTF8String:inet_ntoa(server.sin_addr)];
    }
    return nil;
}

/**
 URL编码
 */
- (NSString *)urlEncoding{
    NSString *str =(NSString*) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8));
    return [str stringByReplacingOccurrencesOfString:@"%20" withString:@"+"];
}

/**
 URL解码
 */
- (NSString *)urlDecoding{
    return [[self stringByReplacingOccurrencesOfString:@"+" withString:@" "] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

- (BOOL)isMobileNum
{
    NSString *phoneRegex = @"^1[0-9]{10}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:self];
}
@end
